import request from '@/common/lib/requestPlus.js'
var dry = {};

dry.set = function(name, data)
{
    return uni.setStorageSync(name, data);
};

dry.get = function(name)
{
    return uni.getStorageSync(name);
};

dry.remove = function(name)
{
    return uni.removeStorageSync(name);
};

dry.setJson = function(name, data)
{
    dry.set(name, JSON.parse(data));
};

dry.getString = function(name)
{
    var data = dry.get(name);
    return JSON.stringify(data);
};

dry.setToken = function(token)
{
    return dry.set("token", token);
};

dry.getToken = function()
{
    return dry.get("token");
};

dry.setUser = function(user)
{
    return dry.set("user", user);
};

dry.getUser = function()
{
    return dry.get("user");
};

dry.getOpenId = function()
{
    return dry.getUser().dry_wei_xin_sp_open_id;
};

dry.getPhone = function()
{
    return dry.getUser().dry_phone;
};

dry.isLogin = function()
{
    const token = dry.getToken();
    if(token){
        return true;
    }
    return false;
};

dry.initUser = function(app, that)
{
    function success(response)
    {
        var user = response.data.data.user;
        app.dry.setUser(user);
        setData();
    }
    
    function setData()
    {
        var data = {
            isLogin: dry.isLogin(),
            user: dry.getUser()
        };
        that.setData(data);
    }
    
    var token = dry.getToken();
    var user = dry.getUser();
    if(token){
        if(user){
            setData();
        }
        else{
            var data = {
                device: app.config.device,
                token: token
            };
            app.r().setData(data).setSuccess(app.msg.ifFailStop).setSuccess(success).run("getUser");
        }
    }
};

dry.updateUser = function(app, that, cb)
{
    function success(response)
    {
        var user = response.data.data.user;
        app.dry.setUser(user);
        setData();
    }
    
    function setData()
    {
        var data = {
            isLogin: dry.isLogin(),
            user: dry.getUser()
        };
        that.setData(data);
        cb();
    }
    
    var token = dry.getToken();
    if(token){
        var data = {
            device: app.config.device,
            token: token
        };
        app.r().setData(data).setSuccess(app.msg.ifFailStop).setSuccess(success).run("getUser");
    }
};

dry.startUpdateUser = function(app, that)
{
    if(app.data.updateUserHandleId){
        clearTimeout(app.data.updateUserHandleId);
    }
    app.data.updateUserHandleId = setTimeout(function(){
        dry.updateUser(app, that, function(){
            dry.startUpdateUser(app, that);
        });
    }, 5000);
};

dry.stopUpdateUser = function(app, that)
{
    clearTimeout(app.data.updateUserHandleId);
};

dry.logout = function()
{
    dry.clear();
    var data = {
        isLogin: false,
        user: null
    };
    that.setData(data);
};

dry.getCostCategory = function() {
	var token = dry.getToken();
	var data = request.run("getCostCategory",token);
	return new Promise((resolve) => {
		uni.request({
			url: data.url,
			method: data.method,
			header: data.header,
			data: {},
			success: res => {
				var costCategory = res.data;
				var newList = dry.setTextAndValue(costCategory);
				resolve(newList);
				
			}
		});
	});
};

dry.setTextAndValue = function (costCategory) {
	var newList = [];
	if(costCategory.length > 0) {
		costCategory.forEach(item => {
			var child = [];
			if(item.children != null) {
				item.children.forEach(e => {
					child.push({
						id: e.id,
						creator: e.creator,
						parentId: e.parentId,
						text: e.name,
						value: e.parentId + '-' + e.id
					})
				})
			}
			newList.push({
				id: item.id,
				creator: item.creator,
				parentId: item.parentId,
				text: item.name,
				value: item.id + '-' + 0,
				children: child
			})
		})
	}
	return newList;
};

dry.getImgIds = function(images,fileIds,delId) 
{
	images.forEach(i => {
		fileIds.push(i.id);
	})
	if(delId.length != 0) {
		delId.forEach(d => {
			if(fileIds.includes(d)) {
				fileIds.splice(fileIds.indexOf(d),1);
			}
		})
	}
	return fileIds;
};

dry.getTeams = function(isCreator) {
	var token = dry.getToken();
	var data = request.run("listTeam", token);
	return new Promise((resolve) => {
		uni.request({
			url: data.url,
			method: data.method,
			header: data.header,
			data: {
				"isCreator": isCreator
			},
			success: res => {
				resolve(res.data);
			}
		})
	})
};

dry.getTeamById = function(id){
	var token = dry.getToken();
	if(token){
		var data = request.run("getTeamById",token);
		return new Promise((resolve) => {
			uni.request({
				url: data.url,
				method: data.method,
				header: data.header,
				data: {
					"id": id
				},
				success: data => {
					resolve(data.data);
				}
			})
		})
	}
};

dry.clear = function()
{
    dry.remove("wxUserInfo");
    dry.remove("token");
    dry.remove("user");
};

dry.parse = function(data)
{
    var children = [];
    var hasParent = [];
    var topList = [];
    for(var i in data){
        var item = data[i];
        hasParent[item.id] = false;
        if(item.dry_parent > 0){
            hasParent[item.id] = true;
            if(!children[item.dry_parent]){
                children[item.dry_parent] = [];
            }
            children[item.dry_parent].push(item);
        }
        if(!hasParent[item.id]){
            topList.push(item);
        }
    }
    return {"topList": topList, "children": children};
};

dry.getEventData = function(e)
{
    return e.currentTarget.dataset;
};

dry.getCurrentYear = function()
{
    return new Date().getFullYear();
};

dry.file2base64 = function(path)
{
    return wx.getFileSystemManager().readFileSync(path, 'base64');
};

dry.getFileSize = function(i)
{
    var KB = 1024;
    var MB = KB * 1024;
    var GB = MB * 1024;
    var value = 0;
    var unit = "";
    if(i < KB){
        value = i;
        unit = "Byte";
    }
    else if(i < MB){
        value = i / KB;
        unit = "KB";
    }
    else if(i < GB){
        value = i / MB;
        unit = "MB";
    }
    else{
        value = i / GB;
        unit = "GB";
    }
    value = value.toFixed(2);
    return {
        "value": value,
        "unit": unit,
        "data": value + unit
    };
};

dry.getDateTimeData = function(i = 0)
{
    function add0(m)
    {
        if(m < 10){
            return "0" + m;
        }
        return m;
    }

    var now = new Date();
    if(i){
        now = new Date(i * 1000);
    }
    var result = {
        "Y": now.getFullYear(),
        "m": add0(now.getMonth() + 1),
        "d": add0(now.getDate()),
        "H": add0(now.getHours()),
        "i": add0(now.getMinutes()),
        "s": add0(now.getSeconds())
    };
    result.standard = result.Y + "-" + result.m + "-" + result.d + " " + result.H + ":" + result.i + ":" + result.s;
    return result;
};

/*
    [min, max]
*/
dry.mtRand = function(min, max)
{
    var result = Math.random() * (max - min + 1) + min;
    return parseInt(result);
};

dry.makeRandOssObjectName = function(timestamp)
{
    var result = dry.getDateTimeData(timestamp);
    return result.Y + "/" + result.m + "/" + result.d + "/" + result.H + "" + result.i + "" + result.s + "-" + dry.mtRand(100000, 999999);
};

dry.getFileExt = function(name)
{
    var position = name.lastIndexOf(".");
    if(position <= 0){
        return "";
    }
    var ext = name.substr(position).toLowerCase();
    return ext;
};

dry.previewImage = function(url)
{
    wx.previewImage({urls: [url]});
};

dry.formatTime = function(data)
{

    function padding(value)
    {
        if(value < 10){
            return `0${value}`;
        }
        else{
            return value;
        }
    }

    var i = parseInt(data);
    var h = Math.floor(i / 3600);
    var m = Math.floor((i - h * 3600) / 60);
    var s = i % 60;
    var list = [];
    if(h > 0){
        list.push(padding(h));
    }
    list.push(padding(m));
    list.push(padding(s));
    return list.join(":");
};

module.exports = dry;